// 日记相关接口,包括新增日记,删除日记,查询日记,模糊查询日记
const express = require("express")
const router = express.Router()
// 引入连接池
const pool = require("../pool/pool")
// 引入封装后的响应
const Response = require("../utils/Response")
// 引入表单验证部分
const Joi = require("joi")
// 新增日记接口
router.post("/pet-diary/add", (req, res) => {
  let { d_img, d_man_name, d_city, d_time, d_detail } = req.body
  let schema = Joi.object({
    d_img: Joi.string().required(),
    d_man_name: Joi.string().required(),
    d_city: Joi.string().required(),
    d_time: Joi.required(),
    d_detail: Joi.string().required(),
  })
  let { error, value } = schema.validate(req.body)
  if (error) {
    res.send(Response.error(error))
    return
  }
  let sql = `insert into pet_diary values (?,?,?,?,?,?)`
  pool.query(
    sql,
    [, d_img, d_man_name, d_city, d_time, d_detail],
    (err, result) => {
      if (err) {
        res.send(Response.error(500, err))
        throw err
      }
      res.send(Response.ok())
    }
  )
})
// 查询日记接口
router.get("/pet-diary", async (req, res) => {
  // 表单验证
  let schema = Joi.object({
    page: Joi.number().required(),
    pagesize: Joi.number().integer().max(50).required(),
  })
  let { error, value } = schema.validate(req.query)
  if (error) {
    res.send(Response.error(error))
    return
  }
  // 执行查询数组
  try {
    let { page, pagesize } = req.query
    let startIndex = (page - 1) * pagesize
    let size = parseInt(pagesize)
    let sql = "select * from pet_diary limit ?,?"
    let result = await pool.querySync(sql, [startIndex, size])
    // 查询总数量
    let sql2 = "select count(*) as count from pet_diary"
    let result2 = await pool.querySync(sql2, [startIndex, size])
    let total = result2[0].count
    res.send(
      Response.ok({ page: parseInt(page), pagesize: size, total, result })
    )
  } catch (error) {
    res.send(Response.error(error))
  }
})
// 删除日记接口
router.post("/pet-diary/del", (req, res) => {
  let { d_id } = req.body
  let schema = Joi.object({
    d_id: Joi.string().required(),
  })
  let { error, value } = schema.validate(req.body)
  if (error) {
    res.send(Response.error(400, error))
    return
  }
  let sql = "delete from pet_diary where d_id=?"
  pool.query(sql, [d_id], (error, result) => {
    if (error) {
      res.send(Response.error(500, error))
      throw error
    }
    res.send(Response.ok())
  })
})

module.exports = router
